package com.tsystems.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import com.tsystems.entities.Passenger;
import com.tsystems.entities.Ticket;
import com.tsystems.entities.TimeTableElement;

public class TicketDAO extends AbstractDAO<Ticket> {

	public List<Ticket> getTickestByTTE(TimeTableElement timeTableElement) {

		EntityManager em = TrainsEntityManager.getInstance();
		CriteriaBuilder builder = em.getCriteriaBuilder();
		CriteriaQuery<Ticket> criteria = builder.createQuery(Ticket.class);

		Root<Ticket> tickets = criteria.from(Ticket.class);
		criteria.select(tickets);
		criteria.where(builder.equal(tickets.get("timeTableElement"),
				timeTableElement));
		List<Ticket> result = em.createQuery(criteria).getResultList();

		return result;
	}

	public List<Ticket> getTicketsByPassenger(Passenger passenger) {

		EntityManager em = TrainsEntityManager.getInstance();
		CriteriaBuilder builder = em.getCriteriaBuilder();
		CriteriaQuery<Ticket> criteria = builder.createQuery(Ticket.class);

		Root<Ticket> tickets = criteria.from(Ticket.class);
		criteria.select(tickets);
		criteria.where(builder.equal(tickets.get("passenger"), passenger));
		List<Ticket> result = em.createQuery(criteria).getResultList();

		return result;
	}

	public Ticket getTicketsByPassengerAndTTE(Passenger passenger,
			TimeTableElement element) {

		EntityManager em = TrainsEntityManager.getInstance();
		CriteriaBuilder builder = em.getCriteriaBuilder();
		CriteriaQuery<Ticket> criteria = builder.createQuery(Ticket.class);

		Root<Ticket> tickets = criteria.from(Ticket.class);
		criteria.select(tickets);
		criteria.where(builder.and(
				builder.equal(tickets.get("passenger"), passenger),
				builder.equal(tickets.get("timeTableElement"), element)));
		List<Ticket> result = em.createQuery(criteria).getResultList();

		return !result.isEmpty() ? result.get(0) : null;
	}

	public List<Ticket> getTicketsByTrain(TimeTableElement timeTableElement) {

		EntityManager em = TrainsEntityManager.getInstance();
		CriteriaBuilder builder = em.getCriteriaBuilder();
		CriteriaQuery<Ticket> criteria = builder.createQuery(Ticket.class);

		Root<Ticket> ticket = criteria.from(Ticket.class);
		criteria.select(ticket);
		criteria.where(builder.equal(ticket.get("timeTableElement"),
				timeTableElement));
		List<Ticket> result = em.createQuery(criteria).getResultList();

		return result;
	}

	public void insertNotSafe(Ticket entity) {
		TrainsEntityManager.getInstance().persist(entity);
	}

}
